#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>

struct Stu 
{
	char name[20];
	int age;
};

int cmp_int(const void* p1, const void* p2)
{
	return (*((int*)p1)) - (*((int*)p2));
}

int cmp_struct_name(const void* p1, const void* p2)
{
	return strcmp(((struct Stu*)p1)->name, ((struct Stu*)p2)->name);
}

void print_int(int arr[], int sz)
{
	for (int i = 0;i < sz;i++)
	{
		printf("%d ", arr[i]);
	}
}

void print_struct_name(struct Stu arr[], int sz)
{
	for (int i = 0;i < sz;i++)
	{
		printf("%s ", arr[i].name);
	}
}

void Swap(char* p1, char* p2, size_t size)
{
	for (size_t i = 0;i < size;i++)
	{
		char temp = '0';
		temp = *p1;
		*p1 = *p2;
		*p2 = temp;
		p1++;
		p2++;
	}
}

void bubble_sort(void* base, size_t num, size_t size,int(*cmp)(const void*, const void*))
{
	for (int i = 0;i < num - 1;i++)
	{
		for (int j = 0;j < num - 1 - i;j++)
		{
			if (cmp((char*)base + j * size, (char*)base + (j+1) * size) > 0)
			{
				Swap((char*)base + j * size, (char*)base + (j + 1) * size, size);
			}
		}
	}
}

test1()
{
	int arr[10] = { 10,9,8,7,6,5,4,3,2,1 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
	print_int(arr, sz);
}

test2()
{
	struct Stu arr[3] = { {"zhangsan",18},{"lisi",35},{"wangwu",25}};
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubble_sort(arr, sz, sizeof(arr[0]), cmp_struct_name);
	print_struct_name(arr, sz);
}

int main()
{	
	test1();	//排序int类型的数据(升序)
	printf("\n");
	test2();	//排序结构体类型的数据（第一个元素字符串，降序）
	printf("\n");
	return 0;
}
